//
//  AVAudioRecorderManager.m
//  Image圆角优化
//
//  Created by 宜必鑫科技 on 2017/12/1.
//  Copyright © 2017年 宜必鑫科技. All rights reserved.
//

#import "AVAudioRecorderManager.h"
#import <Speech/Speech.h>
#import "MBManager.h"

@interface AVAudioRecorderManager()<SFSpeechRecognitionTaskDelegate>

/** 录音设备 */
@property (nonatomic, strong) AVAudioRecorder *recorder;
/** 定时器 */
@property (nonatomic, strong) NSTimer *timer;
/** 定时器 */
@property (nonatomic, assign) int second;
/** 是否授权 */
@property (nonatomic, assign) BOOL isAuthorize;
@end

@implementation AVAudioRecorderManager

+ (instancetype)shareManager
{
    static AVAudioRecorderManager *instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[AVAudioRecorderManager alloc]init];
        [instance permissionsChecking];
    });
    return instance;
}

- (instancetype)init
{
    self = [super init];
    [self setupRecorder];
    return self;
}

/** 设置录音环境 */
- (void)setupRecorder
{
    // 1. 音频会话
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:NULL];
    
    // 参数设置
    NSDictionary *recordSettings = [[NSDictionary alloc] initWithObjectsAndKeys:
                                    [NSNumber numberWithFloat: 14400.0], AVSampleRateKey,
                                    [NSNumber numberWithInt: kAudioFormatAppleIMA4], AVFormatIDKey,
                                    [NSNumber numberWithInt: 2], AVNumberOfChannelsKey,
                                    [NSNumber numberWithInt: AVAudioQualityMax], AVEncoderAudioQualityKey,
                                    nil];
    
    NSString *recordPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"record.caf"];
    _recordURL = [NSURL fileURLWithPath:recordPath];
    _recorder = [[AVAudioRecorder alloc] initWithURL:_recordURL settings:recordSettings error:NULL];
}



///> 开始录音
- (void)startRecorderWithRestlt:(void (^)(BOOL isSuccess))result
{
    if (!_isAuthorize)
    {
        [self permissionsChecking];
        result(false);
    }
    else
    {
        if (!self.timer)
            _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateSecond:) userInfo:nil repeats:YES];
        //启动时间为现在
        [self.timer setFireDate:[NSDate date]];
        [self.recorder record];
        result(true);
    }
}

///> 结束录音
- (void)stopRecorderWithRestlt:(void (^)(BOOL isSuccess))result
{
    if (!_isAuthorize)
    {
        [self permissionsChecking];
        result(false);
    }
    else
    {
        //如果已被释放则return！isValid对应invalidate
        if (!self.timer) return;
        //启动时间为很久以后
        [self.timer setFireDate:[NSDate distantFuture]];
        _second = 0;
        [self.recorder stop];
        result(true);
        if (self.changeTimeStr) {
            self.changeTimeStr([self convertTimeToString:_second]);
        }
    }
}

///> 显示录音的时间
- (void)updateSecond:(NSTimer *)timer
{
    _second ++;
    if (self.changeTimeStr) {
        self.changeTimeStr([self convertTimeToString:_second]);
    }
}

//规范时间格式
- (NSString *)convertTimeToString:(NSInteger)second
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HH:mm:ss"];
    NSDate *date = [formatter dateFromString:@"00:00:00"];
    date = [date dateByAddingTimeInterval:second];
    NSString *timeString = [formatter stringFromDate:date];
    return timeString;
}
///> 权限验证
- (void)permissionsChecking
{
    [SFSpeechRecognizer  requestAuthorization:^(SFSpeechRecognizerAuthorizationStatus status) {
        dispatch_async(dispatch_get_main_queue(), ^{
            switch (status) {
                case SFSpeechRecognizerAuthorizationStatusNotDetermined:
                    _isAuthorize = NO;
                    break;
                case SFSpeechRecognizerAuthorizationStatusDenied:
                     _isAuthorize = NO;
                    break;
                case SFSpeechRecognizerAuthorizationStatusRestricted:
                     _isAuthorize = NO;
                    break;
                case SFSpeechRecognizerAuthorizationStatusAuthorized:
                     _isAuthorize = YES;
                    break;
                default:
                     _isAuthorize = NO;
                    break;
            }
        });
    }];
}

@end
